import store from "@/store/index.js"
import { app } from "@/main.js"
import * as Travel from "@/core/constant/travel.js"
import {navToTravel} from "@/core/app.js"
import * as TravelApi from "@/api/travel/travel.js"

let noticeGap = 6*1000*10 // 1min跳转提醒

class TravelTimer{
	constructor(waitSeconds,travels){
		this.timer = null
		this.waitSeconds = waitSeconds
		this.travels = this.processTravel(travels)
	}
	
	processTravel(travels){
		let result = []
		for(const travel of travels){
			result.push({...travel,countdown:0,status:Travel.TRAVEL_NOT_GOING})
		}
		return result
	}
	
	travelTiming(){
		for(const [index,travel] of this.travels.entries()){
			if(travel.countdown === 0){
				travel.countdown = Date.parse(travel.startTime) - Date.now()
			}else{
				travel.countdown = travel.countdown - this.waitSeconds*1000
			}
			if( travel.countdown < noticeGap){
				if(travel.status === Travel.TRAVEL_WAITING){
					continue
				}
				travel.status = Travel.TRAVEL_WAITING
				const currentTravel = {
					status:travel.status,
					...travel
				}
				console.log("---TravelTimer---")
				console.log(currentTravel)
				store.dispatch("travel/setCurrentTravel",currentTravel)
				navToTravel()	
			}
		}
	}
	
	startTimer(){
		if(this.travels.length === 0){
			return
		}
		this.clearTravelTimer()
		this.timer = setTimeout(() => {
			// 业务方法
			this.travelTiming()
			// 重调timer
			this.startTimer()
		},this.waitSeconds*1000)
	}
	
	clearTravelTimer(){
		 this.timer && clearTimeout(this.timer)
	}

}



export const registerTravelTimer = async (inactiveTravels) => {
	const timer = new TravelTimer(5,inactiveTravels)
	store.commit("travel/SET_TRAVEL_TIMER",timer)
	timer.travelTiming()
	timer.startTimer()
}

export const formatCountdown = (milliseconds) => {
	let formatCountdown = ""
	const seconds =  Math.floor(milliseconds / 1000)
	const minutes = Math.floor(seconds / 60)
	const hours = Math.floor(minutes /  60)
	const days = Math.floor(hours / 24)
	
	if(days > 0){
		formatCountdown += `${days}天`
	}
	
	if(hours > 0){
		formatCountdown += `${hours - days*24}时`
	}
	
	if(minutes > 0){
		formatCountdown += `${minutes - hours*60}分`
	}
	return formatCountdown
}